package com.ukao.steward.ui.valetRunners.storage;


import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ukao.steward.R;
import com.ukao.steward.adapter.StorageAdapter;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.base.PageWrapper;
import com.ukao.steward.bean.OrderInfoBean;
import com.ukao.steward.bean.ReceiptBean;
import com.ukao.steward.bean.StorageListBean;
import com.ukao.steward.dialog.AmountDetailDialogFragment;
import com.ukao.steward.dialog.OrderInfoDialogFragment;
import com.ukao.steward.dialog.SelectNumDialogFragment;
import com.ukao.steward.dialog.TransNoDialogFragment;
import com.ukao.steward.listener.DialogSubmitListener;
import com.ukao.steward.pesenter.valetRunners.StorageListPesenter;
import com.ukao.steward.printer.BluetoothPrintHelper;
import com.ukao.steward.printer.PrintMiuiHelper;
import com.ukao.steward.ui.main.HomeFragment;
import com.ukao.steward.ui.main.MainActivity;
import com.ukao.steward.ui.valetRunners.createOrder.PayOrderFragment;
import com.ukao.steward.util.ActivityUtils;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.T;
import com.ukao.steward.view.valetRunners.StorageListView;
import com.ukao.steward.widget.MyLRecyclerView;
import com.ukao.steward.widget.StateButton;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.steward.R.id.add_btn;
import static com.ukao.steward.R.id.take_send_Carriage;
import static com.ukao.steward.consts.Constant.ARG_PARAM3;
import static com.ukao.steward.consts.Constant.BANEK_REQUEST_CODE;
import static com.ukao.steward.consts.Constant.REQUEST_CODE;


public class StorageListFragment extends MvpFragment<StorageListPesenter> implements StorageListView {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    View view;
    @BindView(R.id.storeName)
    TextView storeName;
    @BindView(R.id.receipt_btn)
    TextView receiptBtn;
    @BindView(R.id.left_bar_btn)
    ImageView leftBarBtn;
    @BindView(R.id.lrecycler_view)
    MyLRecyclerView lrecyclerView;
    @BindView(R.id.line)
    View line;
    @BindView(add_btn)
    ImageView addBtn;
    @BindView(R.id.add_layout)
    LinearLayout addLayout;
    @BindView(R.id.paymentPrice)
    TextView paymentPrice;
    @BindView(R.id.annexTotal)
    TextView annexTotal;
    @BindView(take_send_Carriage)
    TextView takeSendCarriage;
    @BindView(R.id.complete_storage_btn)
    TextView completeStorageBtn;
    @BindView(R.id.take_send_Carriage_layout)
    LinearLayout takeSendCarriageLayout;
    @BindView(R.id.chage_pice_btn)
    StateButton chagePiceBtn;
    @BindView(R.id.gathering_btn)
    StateButton gatheringBtn;
    @BindView(R.id.enter_potpocket_btn)
    StateButton enterPotpocketBtn;


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Unbinder unbinder;
    private View mEmptyView;
    private StorageAdapter mStorageAdapter;
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private PageWrapper mPageWrapper;
    private String orderId;
    private String orderNo;
    private boolean isloadFinish = false;
    private StorageListBean.OrderInfoBean orderInfo;
    private StorageListBean mStorageListBean;
    private String modifyPrice;
    private boolean isPaid;
    private String storeId;

    private TextView collecttv;
    private String packUplist;
    private String addExpand;
    private  boolean  isBackEnterOrderdetail;

    public static Builder createBuilder() {
        return new Builder();
    }
    public static final class Builder {



        private String orderNo;
        private  String  orderId;
        private String storeId ;
        private  boolean  isBackEnterOrderdetail;
        public Builder() {
        }

        /**
         * 是否返回时进入订单详情
         * @param val
         * @return
         */
        public Builder isBackEnterOrderdetail(boolean val) {
            isBackEnterOrderdetail = val;
            return this;
        }
        public Builder orderNo(String val) {
            orderNo = val;
            return this;
        }

        public Builder orderId(String var) {
            this.orderId= var;
            return this;
        }
        public Builder storeId(String  var) {
            this.storeId= var;
            return this;
        }


        public StorageListFragment build() {
            return StorageListFragment.newInstance(orderId,orderNo,  storeId, isBackEnterOrderdetail);
        }
    }


    public static StorageListFragment newInstance(String orderId, String orderNo, String storeId,boolean isBackEnterOrderdetail) {
        StorageListFragment fragment = new StorageListFragment();
        Bundle args = new Bundle();
        args.putString("orderId", orderId);
        args.putString("orderNo", orderNo);
        args.putString("storeId", storeId);
        args.putBoolean("isBackEnterOrderdetail", isBackEnterOrderdetail);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            orderNo = getArguments().getString("orderNo");
            orderId = getArguments().getString("orderId");
            storeId = getArguments().getString("storeId");
            isBackEnterOrderdetail = getArguments().getBoolean("isBackEnterOrderdetail");
        }
    }

    @Override
    protected StorageListPesenter createPresenter() {
        return new StorageListPesenter(this);
    }

    @Override
    protected void initView() {
        addExpand = getString(R.string.add_expand);
        packUplist = getString(R.string.pack_up_list);
        initLinearRecyclerView(lrecyclerView);
        mEmptyView = view.findViewById(R.id.empty_view);
        List<StorageListBean.ProListBean> mData = new ArrayList<>();
        mStorageAdapter = new StorageAdapter(_mActivity, mData);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mStorageAdapter);
        lrecyclerView.setAdapter(mLRecyclerViewAdapter);
        lrecyclerView.setLoadMoreEnabled(false);

    }

    private void addFooterView() {
        if (mLRecyclerViewAdapter.getFooterView() == null) {
            View view = LayoutInflater.from(_mActivity).inflate(R.layout.strorage_foot_layout, null);
            this.collecttv = view.findViewById(R.id.collect_tv);
            collecttv.setOnClickListener(v -> {
                List<StorageListBean.ProListBean> mProListData = mStorageAdapter.getDataList();
                if (CheckUtils.isEmpty(mProListData)) return;
                for (StorageListBean.ProListBean proListBean : mProListData) {
                    if (getText(collecttv).equals(addExpand)) {
                        proListBean.setUnfold(true);
                    } else {
                        proListBean.setUnfold(false);

                    }
                    mStorageAdapter.notifyDataSetChanged();
                }
                collecttv.setText(getText(collecttv).equals(addExpand) ? packUplist : addExpand);
            });

            mLRecyclerViewAdapter.addFooterView(view);
        }

    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        setStatusBarTintColor(R.color.colorPrimary);
        if (!isloadFinish)
            lrecyclerView.forceToRefresh();
    }


    @Override
    protected void initListener() {
        super.initListener();
        lrecyclerView.setOnRefreshListener(() -> mvpPresenter.queryOrder(orderNo, storeId));
        mStorageAdapter.setOnItemChildClickListener((id, pos, item) -> {

            StorageListBean.ProListBean mItem = mStorageAdapter.getItem(pos);
            if (mItem == null) return;
            switch (id) {
                case R.id.subtotal: /*展开*/
                    if (mItem.isUnfold()) {
                        mItem.setUnfold(false);
                    } else {
                        mItem.setUnfold(true);
                    }
                    mStorageAdapter.notifyItemChanged(pos);
                    break;
                case R.id.take_picture_layout:  /*拍照*/
                    if (mItem.getPicCnt() == 0) {
                        Intent intent = ActivityUtils.JumpCameraActivity(_mActivity);
                        intent.putExtra(ARG_PARAM1, mItem.getId());
                        intent.putExtra(ARG_PARAM3, mItem.getPicCnt());
                        startActivityForResult(intent, REQUEST_CODE);
                    } else {
                        startForResult(PhotoFragment.newInstance(mItem), BANEK_REQUEST_CODE);

                    }


                    break;
                case R.id.layout:
                    if (paymentCompleted()) return;
                    if (!CheckUtils.isEmpty(orderId)&&mItem.isClothing())
                        startForResult(AddClothingFragment.newInstance(orderId, mItem, mItem.getNo()), REQUEST_CODE);


                    break;
                case R.id.cope_btn: /*复制*/
                    if (paymentCompleted()) return;
                    mvpPresenter.copy(mItem.getId());
                    break;
                case R.id.delete_btn: /*删除*/
                    if (paymentCompleted()) return;
                    int cloCnt = 0;
                    List<StorageListBean.ProListBean> mData = mStorageAdapter.getDataList();
                    for (StorageListBean.ProListBean proListBean : mData) {
                        if (proListBean.isClothing()) {
                            cloCnt = cloCnt + 1;
                        }
                    }
                    if (cloCnt ==1&&mItem.isClothing()) {
                        T.show(getString(R.string.eep_least_one_garment));
                        return;
                    }
                    mvpPresenter.delete(mItem);
                    break;
                case R.id.bing_btn:
                    showTransNoDialogFragment(mItem);
                    break;
            }
        });

    }

    private boolean paymentCompleted() {
        if (mStorageListBean.isPaymentCompleted()) {
            T.show(getString(R.string.finish_pay_no_play));
            return true;
        }
        return false;
    }

    /**
     * 绑标
     */
    private void showTransNoDialogFragment(StorageListBean.ProListBean mItem) {

        TransNoDialogFragment.createBuilder(getChildFragmentManager())
                .clothingId(mItem.getId())
                .mTitle(getString(R.string.tie_the))
                .isAddTransNo(false)
                .EditTextHide(getString(R.string.please_enter_tag_number))
                .error(getString(R.string.tag_number))
                .mListener((DialogSubmitListener) (parent, message) -> {
                    mItem.setBindCode((String) message);
                    mStorageAdapter.notifyDataSetChanged();
                })
                .show();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_storage_list, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void queryOrderSuccceed(StorageListBean model) {

        isloadFinish = true;
        mStorageListBean = model;
        orderInfo = model.getOrderInfo();
        orderId = orderInfo.getId();
        storeName.setText(orderInfo.getStoreName());
        orderNo = orderInfo.getOrderNo();
        receiptBtn.setVisibility(model.isIsEnablePrint() ? View.VISIBLE : View.GONE);
        mStorageAdapter.setDataList(model.getProList());
        if (collecttv != null) {
            collecttv.setText(addExpand);
        }
        mEmptyView.setVisibility(CheckUtils.isEmpty(model.getProList()) ? View.VISIBLE : View.GONE);
        if (!CheckUtils.isEmpty(model.getProList())) {
            addFooterView();
        }
        paymentPrice.setText("￥" + orderInfo.getPaymentPrice()); /*金额*/
        takeSendCarriageLayout.setVisibility(model.isIsEnableFinishStockIn() ? View.VISIBLE : View.GONE); /*入库layout*/
        annexTotal.setText("衣物" + model.getProTotal() + "件，" + model.getAnnexTotal());
        int sendTakeCarriages = orderInfo.getSendCarriage() + orderInfo.getTakeCarriage();
        takeSendCarriage.setVisibility(sendTakeCarriages == 0 ? View.GONE : View.VISIBLE);
        takeSendCarriage.setText(sendTakeCarriages == 0 ? "" : "加收" + CheckUtils.isEmptyNumber(sendTakeCarriages) + "取送费");
        chagePiceBtn.setVisibility(model.isIsEnableModifyPrice() && !model.isIsPaid() ? View.VISIBLE : View.INVISIBLE); /*修改价格*/
        // enterPotpocketBtn.setVisibility(model.isEnableBatchIn() ? View.VISIBLE : View.INVISIBLE);/*入袋*/
        gatheringBtn.setVisibility(model.isIsEnablePay() && !model.isIsPaid() ? View.VISIBLE : View.INVISIBLE);
        modifyPrice = orderInfo.getIsModifyPrice() ? orderInfo.getPaymentPrice() : "";  /*修改金额*/
        isPaid = model.isIsPaid();

    }

    @Override
    public void queryOrderFinish() {

        lrecyclerView.refreshFinish();
    }

    /**
     * 完成入库
     */
    @Override
    public void stockInfinishSucceed() {
        takeSendCarriageLayout.setVisibility(View.GONE);
        receiptBtn.setVisibility(View.VISIBLE);
        // enterPotpocketBtn.setVisibility(View.VISIBLE);
        if (mStorageListBean != null) {
            mStorageListBean.setIsEnableFinishStockIn(false);
            orderInfo.setStatusText("已入库");
            mStorageListBean.setIsEnablePrint(true);
            if (!mStorageListBean.isIsPaid()) {
                chagePiceBtn.setVisibility(View.VISIBLE);
                gatheringBtn.setVisibility(View.VISIBLE);


            }
        }

    }

    /**
     * 打印小票
     *
     * @param mReceiptBean
     */
    @Override
    public void loadReceipt(ReceiptBean mReceiptBean) {

        if (CheckUtils.isMIUIDevices()) {
            PrintMiuiHelper.receiptReceipt(MainActivity.getPrintService(), mReceiptBean);
        } else {
            BluetoothPrintHelper.receiptReceipt(_mActivity, mReceiptBean);
        }

    }

    @Override
    public void codeSucceed() {
        lrecyclerView.forceToRefresh();
    }

    @Override
    public void deleteSucceed(StorageListBean.ProListBean mProListBean) {
        isloadFinish = false;
        lrecyclerView.forceToRefresh();
    }


    /**
     * 支付订单信息
     *
     * @param mPayOrderInfoBean
     */
    @Override
    public void payOrderInfoData(OrderInfoBean mPayOrderInfoBean) {
        mPayOrderInfoBean.setPayFinisEnterOrderDetails(true);
        start(PayOrderFragment.newInstance(orderId, mPayOrderInfoBean), SINGLETASK);

    }


    /**
     * 修改金额
     *
     * @param mModifyPrice
     */
    @Override
    public void storageModifyPrice(String mModifyPrice) {
        paymentPrice.setText("￥" + mModifyPrice);
        modifyPrice = mModifyPrice;

    }



//    if (mStorageListBean != null) {
//        mStorageListBean.setIsPaid(true);
//        mStorageListBean.setPaymentCompleted(true);
//    }


    @Override
    public boolean onBackPressedSupport() {
        closeOtherFragment();


        return true;
    }

    void closeOtherFragment() {
        try{
            if (isAdded()&&findFragment(StorageListFragment.class)!=null){
                if (isBackEnterOrderdetail){
                    finish();
                }else{
                    popTo(HomeFragment.class, false);
                }
            }

        }catch (Exception e){

        }


    }

    @OnClick({R.id.receipt_btn, R.id.left_bar_btn, add_btn, R.id.complete_storage_btn, R.id.chage_pice_btn, R.id.gathering_btn, R.id.enter_potpocket_btn
            , R.id.paymentPrice, R.id.back_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_tv:
                closeOtherFragment();
                break;
            case R.id.paymentPrice:
                if (orderInfo != null) {
                    String mOrderPrice = CheckUtils.isEmptyNumber(orderInfo.getOrderPrice());
                    String sendCarriage = CheckUtils.isEmptyNumber(orderInfo.getSendCarriage());
                    String takeCarriage = CheckUtils.isEmptyNumber(orderInfo.getTakeCarriage());
                    setDrawableRight(R.drawable.storage_list_pull_up);
                    AmountDetailDialogFragment mOrderInfoDialog = AmountDetailDialogFragment.newInstance(mOrderPrice, sendCarriage, takeCarriage, modifyPrice);
                    mOrderInfoDialog.setOnSubmitClickListener((DialogSubmitListener) (parent, message) -> setDrawableRight(R.drawable.storage_list_pull_down));
                    mOrderInfoDialog.show(getChildFragmentManager(), AmountDetailDialogFragment.class.getName());
                }
                break;
            case R.id.receipt_btn:
                if (CheckUtils.isEmpty(orderId)) return;
                mvpPresenter.printReceipt(orderId);
                break;
            case R.id.left_bar_btn:
                if (orderInfo != null && mStorageListBean != null) {
                    OrderInfoDialogFragment mOrderInfoDialog = OrderInfoDialogFragment.newInstance(orderInfo, isPaid, mStorageListBean.isIsEnablePrint());
                    mOrderInfoDialog.setOnSubmitClickListener((DialogSubmitListener) (parent, message) -> {
                        mvpPresenter.printReceipt(orderId);
                    });
                    mOrderInfoDialog.show(getChildFragmentManager(), OrderInfoDialogFragment.class.getName());
                }

                break;
            case add_btn:  //添加衣物
                if (orderInfo != null)
                    startForResult(AddClothingFragment.newInstance(orderInfo.getId(), null, mStorageListBean.getProList().size()), REQUEST_CODE);

                break;
            case R.id.complete_storage_btn:
                if (CheckUtils.isEmpty(orderId)) return;
                mvpPresenter.stockInfinish(orderId);
                break;
            case R.id.chage_pice_btn:
                if (CheckUtils.isEmpty(orderId)) return;

                String unitPice = "订单金额" + ":" + getText(paymentPrice);
                SelectNumDialogFragment.createBuilder(getFragmentManager()).setmDialogTitle("修改订单总额").
                        setUnitTitle("元").setUnitPice(unitPice).setModificationVisibility(true).
                        setListener((DialogSubmitListener) (parent, message) -> {
                            mvpPresenter.storageModifyPrice(orderId, (String) message);

                        }).show();


                break;
            case R.id.gathering_btn:
                if (CheckUtils.isEmpty(orderId)) return;
                mvpPresenter.unlockOrder(orderId);
                break;
            case R.id.enter_potpocket_btn:
                break;
        }
    }

    private void setDrawableRight(int id) {
        Drawable drawable = getResources().getDrawable(id);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        paymentPrice.setCompoundDrawables(null, null, drawable, null);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE:/*获取照片数量*/
                    isloadFinish = false;
                    lrecyclerView.forceToRefresh();


                    break;

            }
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE:
                    isloadFinish = false;
                    lrecyclerView.forceToRefresh();
                    break;
                case BANEK_REQUEST_CODE:  /*拍照数据返回*/
                    StorageListBean.ProListBean mProListBean = data.getParcelable(ARG_PARAM1);
                    if (CheckUtils.isNull(mProListBean)) return;
                    int indexOf = mStorageAdapter.getDataList().indexOf(mProListBean);
                    if (indexOf != -1) {
                        mStorageAdapter.notifyItemChanged(indexOf);
                    }


                    break;
            }
        }
    }


}
